# encoding: utf-8
class ExamsController < ApplicationController
  # GET /exams
  # GET /exams.json
  def index
    @exams = Exam.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @exams }
    end
  end

  # GET /exams/1
  # GET /exams/1.json
  def show
    @exam = Exam.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @exam }
    end
  end

  # GET /exams/new
  # GET /exams/new.json
  def new
    @exam = Exam.new
    @groups = YAML.load(Mconfig.find_by_cname("groups").cvalue)
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @exam }
    end
  end

  # GET /exams/1/edit
  def edit
    @exam = Exam.find(params[:id])
  end

  # POST /exams
  # POST /exams.json
  def create
    @exam = Exam.new(params[:exam])
    @groups = YAML.load(Mconfig.find_by_cname("groups").cvalue)
    respond_to do |format|
      if @exam.save
        begin
          Exam.transaction do
            sgroups = []
            logger.debug "开始"<<Time.now.to_s
            @groups.each do |g|
              if (params[g].to_s =="on")
                sgroups<<g
              end
            end
            logger.debug "获取分班信息结束,开始逐条插入"<<Time.now.to_s
            if sgroups.size >0
              @exam.scope = sgroups.to_s
              @exam.save!
              logger.debug "开始逐条插入"<<Time.now.to_s
              students = Student.order("studentId ASC").find_all_by_sgroup(sgroups)
              students.each do |s|
                a = Score.new
                a.student = s
                a.exam = @exam
                a.save!
              end
              logger.debug "逐条插入结束"<<Time.now.to_s
            end
          end
          format.html { redirect_to @exam, notice: '本次考试信息创建成功.' }
          format.json { render json: @exam, status: :created, location: @exam }
        rescue =>e
          @exam.destroy
          logger.error("创建考试信息失败:"<<e.to_s)
        end
      else
        format.html { render action: "new" }
        format.json { render json: @exam.errors, status: :unprocessable_entity }
      end


    end
  end

  # PUT /exams/1
  # PUT /exams/1.json
  def update
    @exam = Exam.find(params[:id])

    respond_to do |format|
      if @exam.update_attributes(params[:exam])
        format.html { redirect_to @exam, notice: 'Exam was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @exam.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /exams/1
  # DELETE /exams/1.json
  def destroy
    @exam = Exam.find(params[:id])
    ActiveRecord::Base.connection().delete_sql("delete from scores where exam_id = "<< @exam.id.to_s)
    @exam.destroy

    respond_to do |format|
      format.html { redirect_to exams_url }
      format.json { head :ok }
    end
  end
end
